package com.manning.unlockingandroid; //1

import com.manning.unlockingandroid.R; //2
import android.app.Activity; //3
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.NumberFormat; //4
import android.util.Log; //5

public class ChapterTwo extends Activity {
    /** Called when the activity is first created. */
	public static final String tag = "Chapter2"; //6
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final EditText mealpricefield = (EditText) findViewById(R.id.mealprice); //7
        final TextView answerfield = (TextView) findViewById(R.id.answer); //8
        final Button button = (Button) findViewById(R.id.Calculate); //9
        button.setOnClickListener(new Button.OnClickListener() { //10;
        	
        	public void onClick(View v)
        	{
        		try {
        			//perform action on click
        			Log.i(tag, "onClick invoked."); //11
        			//grab the meal price from UI
        			String mealprice = mealpricefield.getText().toString(); //12
        			Log.i(tag,"Meal price is[" + mealprice + "]");
        			String answer = "";
        			//check to see if the meal price include a "$"
        			if(mealprice.indexOf("$") == -1)
        			{
        				mealprice = "$" + mealprice;
        			}
        			float fmp = 0.0F;
        			//get current formatter
        			NumberFormat nf = java.text.NumberFormat.getCurrencyInstance(); //13
        			//Grab the input meal price
        			fmp = nf.parse(mealprice).floatValue();
        			//let's give a nice tip -> 20%
        			fmp *= 1.2; //14
        			Log.i(tag,"Total Meal Price (unformatted) is [" + fmp + "]");
        			//format your answer 
        			answer = "Full Price, Including 20% : " + nf.format(fmp); //15
        			//dispaly the answer
        			answerfield.setText(answer); //16
        			Log.i(tag,"onClick Complete");
        		}
        		catch(java.text.ParseException pe) //17
        		{
        			Log.i(tag,"Parse exception caught");
        			answerfield.setText("Failed to parse amount?");
        		}
        		catch(Exception e)
        		{
        			Log.e(tag, "Failed to Calculate tip" + e.getMessage());
        			e.printStackTrace();
        			answerfield.setText(e.getMessage());
        		}
        	}
        }
        );
    }
}
        		
 